#pragma once

#include "TableCommon.h"
#include "TableColumn.h"
#include <map>
#include <list>

namespace qb{
	namespace ht{
		class TableWriter;
		//class Grid;
		class Table;
		class TableUser;
        class DataBase{	// 单例模式
			typedef std::map<int, Table*>	TableMap;
			typedef std::list<TableWriter*>	WriterList;
			typedef std::map<int, WriterList > WriterListMap;
			//HostWindow*		m_window;
			TableMap		m_tablemap;
			WriterListMap	m_writers;
            FastLock		m_lock;
		public:
			static DataBase& Get();
			static void Release();
			DataBase();
			~DataBase();

			/*
				tableid 是个全局的自行设计定义的表格id，之所以不用字符串是为了提升性能
				用户需自行定义所有表的id放在一个全局枚举变量中
				*/
			bool CreateTable(const TableDesc& desc, int tableid, const char* name = 0,bool useldb=false);
			bool RemoveTable(int id);

			bool RegisterUser(TableUser* user, int tableid);
			bool RegisterWriter(TableWriter* writer, int funcid)
			{
				ScopedLock scoped(m_lock);
				WriterListMap::iterator mit = m_writers.find(funcid);
				if (mit == m_writers.end())
				{
					m_writers[funcid] = WriterList();
					mit = m_writers.find(funcid);
				}

				WriterList& wl = mit->second;
				wl.push_back(writer);
				return true;
			}

			Table* GetTable(int tableid);


            void OnUIMessage(uint32_t message, void* wParam, void* lParam)
			{
			}
            void OnNetMessage(int funcid, void* wparam, void* lparam);

			// 后台线程中TableUser变更后，会给UI线程发送通知消息
            void NotifyGrid(void* grid);
			//void RegisterGrid(Grid* grid);
		};
	}//namespace ht
}//namespace qb
